package com.shop.www.controller;

import com.shop.www.model.Cart;
import com.shop.www.model.Order;
import com.shop.www.model.User;
import com.shop.www.service.CartItemservice;
import com.shop.www.service.Orderservice;
import com.shop.www.service.Userservice;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class Usercontroller {
    private Userservice userservice;
    private CartItemservice cartItemservice;
    private Orderservice orderservice;

    public String login(String user_name, String user_psw, HttpSession session,HttpServletResponse response) throws IOException {//登录，并获取购物车
        User user = userservice.userlogin(user_name,user_psw);
        PrintWriter out = response.getWriter();
        if(user!=null) {
            if(user.getState()==0){
                out.println("<script language='javascript'>alert('您已被封禁！请联系管理员解封');</script>");
                return ("login");
            }
            session.setAttribute("loginuser",user);
            return ("redirect:Commodity.do");
        }
        out.println("<script language='javascript'>alert('账号或密码不正确！');</script>");
        return ("login");
    }

     //注册
    public String regist(String verifyCode, String user_name, String user_psw, HttpSession session, HttpServletResponse response) throws IOException {
        Object kaptchaCodeObj = session.getAttribute("KAPTCHA_SESSION_KEY");
        if(kaptchaCodeObj==null || !verifyCode.equals(kaptchaCodeObj)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<script language='javascript'>alert('验证码不正确！');</script>");
            return "regist";
        }else{
            if(verifyCode.equals(kaptchaCodeObj)){
                userservice.regist(new User(user_name,user_psw,2,1));
                return "login";
            }
        }
        return "login";
    }

    //配送员页面
    public String courier(HttpSession session){
        User user = (User)session.getAttribute("loginuser");
        List<Order> orderList = orderservice.getorderlist("3");
        List<Order> acceptorderList = orderservice.getorderListBycourier(user.getUser_ID());
        session.setAttribute("orderList",orderList);
        session.setAttribute("acceptorderList",acceptorderList);
        return ("courier");
    }

    //管理员后台管理
    public String admin(HttpSession session){
        User user = (User) session.getAttribute("loginuser");
        List<User> userList = userservice.getuserlist();
        session.setAttribute("userList",userList);
        return ("admin");
    }

    public String ban(Integer user_ID,Integer state){
        User user = new User(user_ID,state);
        userservice.banuser(user);
        return ("redirect:User.do?operate=admin");
    }

}
